package com.xmjs.baselibrary.base.dialog;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;

import androidx.annotation.CallSuper;
import androidx.annotation.CheckResult;

import com.trello.rxlifecycle3.LifecycleProvider;
import com.trello.rxlifecycle3.LifecycleTransformer;
import com.trello.rxlifecycle3.RxLifecycle;
import com.trello.rxlifecycle3.android.FragmentEvent;
import com.trello.rxlifecycle3.android.RxLifecycleAndroid;

import io.reactivex.Observable;
import io.reactivex.annotations.NonNull;
import io.reactivex.annotations.Nullable;
import io.reactivex.subjects.BehaviorSubject;

/**
 * 具有Lifiecycle生命周期管理的Dialog
 */
public class RxDialog extends Dialog implements LifecycleProvider<FragmentEvent> {
    private final BehaviorSubject<FragmentEvent> lifecycleSubject = BehaviorSubject.create();

    public RxDialog(@NonNull Context context) {
        super(context);
    }

    public RxDialog(@NonNull Context context, int themeResId) {
        super(context, themeResId);
    }

    protected RxDialog(@NonNull Context context, boolean cancelable, @Nullable OnCancelListener cancelListener) {
        super(context, cancelable, cancelListener);
    }


    @Override
    @NonNull
    @CheckResult
    public final Observable<FragmentEvent> lifecycle() {
        return lifecycleSubject.hide();
    }

    @Override
    @NonNull
    @CheckResult
    public final <T> LifecycleTransformer<T> bindUntilEvent(@NonNull FragmentEvent event) {
        return RxLifecycle.bindUntilEvent(lifecycleSubject, event);
    }

    @Override
    @NonNull
    @CheckResult
    public final <T> LifecycleTransformer<T> bindToLifecycle() {
        return RxLifecycleAndroid.bindFragment(lifecycleSubject);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        lifecycleSubject.onNext(FragmentEvent.CREATE);
    }

    @Override
    @CallSuper
    public void onStart() {
        super.onStart();
        lifecycleSubject.onNext(FragmentEvent.START);
    }

    @Override
    @CallSuper
    public void onStop() {
        lifecycleSubject.onNext(FragmentEvent.STOP);
        super.onStop();
    }

    @Override
    public void dismiss() {
        lifecycleSubject.onNext(FragmentEvent.DESTROY);
        super.dismiss();
    }

    @Override
    public void onDetachedFromWindow() {
        lifecycleSubject.onNext(FragmentEvent.DETACH);
        super.onDetachedFromWindow();
    }

    @Override
    public void onAttachedToWindow() {
        lifecycleSubject.onNext(FragmentEvent.ATTACH);
        super.onAttachedToWindow();
    }

    @Override
    public void cancel() {
        lifecycleSubject.onNext(FragmentEvent.DESTROY);
        super.cancel();
    }
}
